<?php

	// +----------------------------------------------------------------------
	// | 商品模型
	// +----------------------------------------------------------------------
	// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
	// +----------------------------------------------------------------------
	// | Author: 微尘 <yicmf@qq.com>
	// +----------------------------------------------------------------------

	namespace app\model\store;

	use app\model\file\Image;
	use app\pay\model\Discount;
	use app\model\store\Store as StoreModel;
	use app\model\ucenter\User;

	class Good extends Common
	{

		public function user()
		{
			return $this->belongsTo(User::class);
		}

		public function store()
		{
			return $this->belongsTo(Store::class);
		}

		/**
		 * 封面
		 */
		public function cover()
		{
			return $this->belongsTo(Image::class, 'cover_id');
		}
        public function image()
        {
            return $this->belongsTo(Image::class,'image_id')->field('id,save_name,url,save_path,driver');
        }


		/**
		 * sku
		 * @author  : 微尘 <yicmf@qq.com>
		 */
		public function skus()
		{
			return $this->hasMany(GoodSku::class)->where('status', 1);
		}

		/**
		 * 评价
		 * @author  : 微尘 <yicmf@qq.com>
		 */
		public function evaluates()
		{
			return $this->hasMany(GoodEvaluate::class)->where('status', 1);
		}


//		public function images()
//		{
//			return $this->belongsToMany(Image::class, GoodImage::class);//->field('id,driver,url,save_name');
//		}

		public function visits()
		{
			return $this->hasMany(GoodVisit::class);
		}
        public function getBodyAttr($value)
        {
            if ($value && stripos($value, 'src="/ueditor/php/upload') !== false) {

                return str_replace('src="/ueditor/php/upload','src="'.self::$request->domain().'/ueditor/php/upload',$value);
            }else{
                return $value;
            }
        }

		public function tags()
		{
			return $this->hasMany(GoodTag::class);
		}

		public function getImagesAttr($value)
		{
			$id = json_decode($value, true);
			if (!empty($id)) {
				return Image::where('id', 'in', $id)->orderRaw('field(id,' . implode(',', $id) . ')')->select();
			} else {
				return [];
			}
		}

		/**
		 * 写入修改
		 * @param $data
		 */
		public static function onBeforeInsert($data)
		{
//			$data['status'] = 1;
			$data['ip'] = request()->ip();
			$data['sale'] = 3;
//			$data['refresh_time'] = time_format();
//			$data['sku_spec_format'] = isset($data['sku_spec_format']) ? $data['sku_spec_format'] : '{}';
		}

		/**
		 * 写入修改
		 * @param $data
		 */
		public static function onBeforeWrite($data)
		{
//			$data['status'] = 1;
			$data['ip'] = request()->ip();
		}


		// 类型转换
		protected $type = [
//			'good_attribute' => 'array',
		];
	}
